<template>
  <div class="page">
    <!-- 顶部大图 + 波浪 -->
    <header class="header">
      <FanPageHeader
        :title="isLogin ? '快点登录叭' : '快点注册吧'"
        subTitle=""
        current="返回首页"
        :img="karina4Img"
      />
      <div class="waves-wrapper">
        <Waves height="6rem" />
      </div>
    </header>

    <!-- 居中登录/注册卡片 -->
    <main class="content">
      <div class="login-card">
        <h2 class="login-title">{{ isLogin ? '登录' : '注册' }}</h2>
        <p class="login-tip">
          {{ isLogin ? '还没有账号？' : '已有账号？' }}
          <a-button type="link" @click="toggleMode">
            {{ isLogin ? '立即注册' : '立即登录' }}
          </a-button>
        </p>

        <a-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          @finish="handleSubmit"
          class="login-form"
        >
          <a-form-item name="username">
            <a-input
              v-model:value="formData.username"
              placeholder="用户名"
              size="large"
              autocomplete="username"
            >
              <template #prefix><UserOutlined /></template>
            </a-input>
          </a-form-item>

          <a-form-item name="email" v-if="!isLogin">
            <a-input
              v-model:value="formData.email"
              placeholder="邮箱（可选）"
              size="large"
              autocomplete="email"
            >
              <template #prefix><MailOutlined /></template>
            </a-input>
          </a-form-item>

          <a-form-item name="password">
            <a-input-password
              v-model:value="formData.password"
              placeholder="密码"
              size="large"
              autocomplete="current-password"
            >
              <template #prefix><LockOutlined /></template>
            </a-input-password>
          </a-form-item>

          <a-form-item name="confirmPassword" v-if="!isLogin">
            <a-input-password
              v-model:value="formData.confirmPassword"
              placeholder="确认密码"
              size="large"
              autocomplete="new-password"
            >
              <template #prefix><LockOutlined /></template>
            </a-input-password>
          </a-form-item>

          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              size="large"
              block
              :loading="loading"
            >
              {{ isLogin ? '登录' : '注册' }}
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </main>
  </div>
</template>

<script setup>
import karina4Img from '@/assets/wrapper/karina4.png'
import { ref, reactive, computed } from 'vue'
import { UserOutlined, LockOutlined, MailOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '../../stores/user'
import { useRouter } from 'vue-router'
import { notification } from 'ant-design-vue'
import FanPageHeader from '@/components/common/FanPageHeader.vue'
import Waves from '@/components/common/waves.vue'

// 状态管理
const userStore = useUserStore()
const router = useRouter()
const formRef = ref()
const loading = ref(false)
const isLogin = ref(true)

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = computed(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (value.length < 3 || value.length > 20) {
          return Promise.reject('用户名长度必须在3-20位之间')
        }
        if (!/^[a-zA-Z0-9]+$/.test(value)) {
          return Promise.reject('用户名只能包含字母和数字')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  email: isLogin.value ? [] : [
    { 
      validator: (rule, value) => {
        if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
          return Promise.reject('请输入正确的邮箱格式')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      validator: (rule, value) => {
        if (value.length < 3 || value.length > 20) {
          return Promise.reject('密码长度必须在3-20位之间')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: isLogin.value ? [] : [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== formData.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}))

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  formRef.value?.clearValidate()
  // 重置表单
  formData.username = ''
  formData.email = ''
  formData.password = ''
  formData.confirmPassword = ''
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 先验证表单
    await formRef.value.validate()
    
    loading.value = true
    // 登录和注册的逻辑
    if (isLogin.value) { 
      // 登录
      const res = await userStore.LoginPinia({
        username: formData.username,
        password: formData.password
      });
      if (res.success) {
        notification.success({
          message: '登录成功',
          description: '欢迎回来！',
          placement: 'topRight'
        })
        router.push({ name: 'index' })
        // 注意：loginStatus 已经在 SetTokenPinia 中设置，不需要手动设置
      } else {
        notification.error({
          message: '登录失败',
          description: res.data || '登录失败',
          placement: 'topRight'
        })
      }
    } else {
      // 注册
      const res = await userStore.RegisterPinia({
        username: formData.username,
        email: formData.email,
        password: formData.password
      });
      if (res.success) {
        notification.success({
          message: '注册成功',
          description: '请登录！',
          placement: 'topRight'
        })
        toggleMode()
      } else {
        notification.error({
          message: '注册失败',
          description: res.data || '注册失败',
          placement: 'topRight'
        })
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    if (error.errorFields) {
      // 表单验证错误，不需要额外处理
      return
    }
    notification.error({
      message: '操作失败',
      description: error.message || '请稍后重试',
      placement: 'topRight'
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 整体布局：同 userInfo */
.page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 头部：同 userInfo */
.header {
  position: relative;
  width: 100%;
  flex-shrink: 0;
}
.waves-wrapper {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 10rem;
  pointer-events: none;
}

/* 内容区：居中卡片 */
.content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem 1rem;
}
.login-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  width: 100%;
  max-width: 400px;
  padding: 32px 36px;
}
.login-title {
  text-align: center;
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: 600;
}
.login-tip {
  text-align: center;
  margin-bottom: 24px;
  color: #666;
}
.login-form .ant-form-item {
  margin-bottom: 16px;
}
</style>